package com.shycloud.mido.organ.api.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

public class PdfToImageUtil {
    private static final Integer DPI = 100;

    private static final String IMG_TYPE = "png";

    public static List<byte[]> pdfToImage(byte[] fileContent) throws IOException {
        List<byte[]> result = new ArrayList<>();
        try (PDDocument document = PDDocument.load(fileContent)) {
            PDFRenderer renderer = new PDFRenderer(document);
            for (int i = 0; i < document.getNumberOfPages(); ++i) {
            	BufferedImage bufferedImage = renderer.renderImageWithDPI(i, DPI);
                try(ByteArrayOutputStream out = new ByteArrayOutputStream()) {
					ImageIO.write(bufferedImage, IMG_TYPE, out);
					result.add(out.toByteArray());
				} 
            }
        }
        return result;
    }
    
}
